﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using VCommons;
using System.IO;

namespace ReadFile.WebService
{
    /// <summary>
    /// CacheFile 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class CacheFile : System.Web.Services.WebService
    { 
        /// <summary>
        /// 缓存日期（最后一次从文件读到的时间）
        /// </summary>
        public static DateTime LastModifyDate { get; private set; }

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        /// <summary>
        /// 加载缓存
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public byte[] LoadCache(string cacheName)
        {
            if (File.Exists(ReturnCachePath(cacheName)))
            {
                var entity= SerializationHelper.Load(typeof(object), ReturnCachePath(cacheName));

                return SerializationHelper.ObjectToByteArray(entity);
             }
            else //如果不存在缓存物理文件，则直接返回NULL，表示缓存没有生成，直接由调用层返回结果，不走缓存
            {

                return null;
            }
        }

        /// <summary>
        /// 保存到缓存文件
        /// </summary>
        /// <param name="cacheName"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [WebMethod]
        public int SaveCache(string cacheName, byte[] entity)
        {
            int flag = 0;
            object obj = SerializationHelper.ByteArrayToObject(entity);
            /// <summary>
            /// 线程锁
            /// </summary>
            object lockHelper = new object();
            lock (lockHelper)
            {
                SerializationHelper.Save(obj, ReturnCachePath(cacheName));
                flag = 1;
            }

            return flag;
        }

        string ReturnCachePath(string cacheName)
        {
            HttpContext context = HttpContext.Current;
            if (context != null)
            {
                cacheName = context.Server.MapPath(string.Format("/Caches/{0}", cacheName));
            }
            else
            {
                cacheName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Caches\{0}", cacheName);
            }
            return cacheName;

        }
    }
}
